package cn.sun.error;

import cn.sun.result.ResultVO;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ExceptionHandlerPage implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        ResultVO<String> data = null;
        if (e instanceof FlowException) {
            data = ResultVO.failed("接口被限流了", "-1");
        } else if (e instanceof DegradeException) {
            data = ResultVO.failed("接口被降级了","-2");
        }else if (e instanceof ParamFlowException) {
            data = ResultVO.failed("参数限流异常","-3");
        }else if (e instanceof AuthorityException) {
            data = ResultVO.failed("授权异常","-4");
        }else if (e instanceof SystemBlockException) {
            data = ResultVO.failed("系统负载异常了...","-5");
        }
        response.getWriter().write(JSON.toJSONString(data));
    }
}
